﻿#include <QTabWidget>
#include <QTimer>
#include <QTabBar>
#include <QProgressBar>
#include <QMessageBox>

#include "CefWebEngineWidgets/CefWebEngineView.h"

#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    ui(new Ui_MainWindow),
    mcurrentView(nullptr),
    mprogressBar(new QProgressBar)
{
    ui->setupUi(this);
    resize(1600, 900);

    connect(ui->tabWidget, &QTabWidget::tabCloseRequested, this, [=](int index) {
        QWidget *widget = ui->tabWidget->widget(index);
        ui->tabWidget->removeTab(index);
        // qt bug 将 parent 设为 nullptr，否则删除时导致整个窗口关闭。
        widget->setParent(nullptr);
        if (widget)
            delete widget;
    });

    auto view = new CefWebEngineView;
    connect(view, &CefWebEngineView::newWindowRequested, this, &MainWindow::setupSubView);
    view->load(QUrl("https://www.baidu.com"));
    addTabPage(view);
    setupCurrentView();

    mprogressBar->setRange(0, 100);
    ui->statusbar->addPermanentWidget(mprogressBar);
    mprogressBar->hide();

    connect(ui->lineEdit_url, &QLineEdit::returnPressed, this, [this]() {
        if (mcurrentView)
            mcurrentView->load(QUrl(ui->lineEdit_url->text()));
    });
    connect(ui->tabWidget, &QTabWidget::currentChanged, this, &MainWindow::setupCurrentView);
    connect(ui->menu_file, &QMenu::triggered, this, &MainWindow::executeActions);
    connect(ui->menu_help, &QMenu::triggered, this, &MainWindow::executeActions);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addTabPage(CefWebEngineView *view)
{
    int index = ui->tabWidget->addTab(view, view->windowIcon(), view->windowTitle());
    ui->tabWidget->setCurrentIndex(index);
    ui->tabWidget->setTabToolTip(index, view->windowTitle());
    connect(view, &CefWebEngineView::windowTitleChanged, this, [=](const QString &title) {
        int index = ui->tabWidget->indexOf(view);
        ui->tabWidget->setTabText(index, title);
        ui->tabWidget->setTabToolTip(index, title);
    });
    connect(view, &CefWebEngineView::windowIconChanged, this, [=](const QIcon &icon) {
        int index = ui->tabWidget->indexOf(view);
        ui->tabWidget->setTabIcon(index, icon);
    });
}

void MainWindow::setupSubView(const QUrl &url, CefWebEnginePage **page)
{
    auto view = new CefWebEngineView;
    connect(view, &CefWebEngineView::newWindowRequested, this, &MainWindow::setupSubView);
    *page = view->setupEmptyPage(url);
    QTimer::singleShot(0, this, [=]() { addTabPage(view); });
}

void MainWindow::setupCurrentView()
{
    for (const QMetaObject::Connection &con : mconns)
        disconnect(con);

    mconns.clear();
    mcurrentView = qobject_cast<CefWebEngineView *>(ui->tabWidget->currentWidget());
    if (!mcurrentView)
        return;

    mconns << connect(mcurrentView, &CefWebEngineView::statusChanged, this, [this](const QString &message) {
        ui->statusbar->showMessage(message);
    });
    mconns << connect(mcurrentView, &CefWebEngineView::urlChanged, this, [this](const QUrl &url) {
        ui->lineEdit_url->setText(url.toString());
    });
    mconns << connect(mcurrentView, &CefWebEngineView::loadProgressChanged, this, [this](int progress) {
        mprogressBar->setValue(progress);
        mprogressBar->setVisible(progress < 100);
    });

    ui->lineEdit_url->setText(mcurrentView->page()->url().toString());
}

void MainWindow::executeActions(QAction *action)
{
    QString name = action->objectName();
    if (name == "exitAction") {
        close();
    }
    else if (name == "printAction") {
        
    }
    else if (name == "openDevToolsAction")
    {
        if (mcurrentView)
        {
            auto devView = new CefWebEngineView;
            devView->setAttribute(Qt::WA_DeleteOnClose);
            devView->setWindowTitle("开发者工具");
            devView->setFixedWindowTitleEnable(true);
            devView->resize(1200, 798);
            mcurrentView->page()->setDevToolsPage(devView->setupEmptyPage(QUrl()));
            devView->show();
        }
    }
    else if (name == "aboutAction") {
        QMessageBox::about(topLevelWidget(), tr("关于"), tr("CEF Qt WebEngine!"));
    }
}